async function post(url, data){
    let res = await fetch(
        url, {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            method: "POST",
            body: urlEncode(data),
            credentials: "same-origin"
        }
    )
    let rep = await res.text();
    return rep;
}

const dir = "/chat-room/"
const url = {
    ws: 'ws://' + window.location.host + '/chat-room',
    send: "api/send",
    creatRoom: "api/room"
}

const client = {
    sender: async (type, id, msg) => {
        let sendData = {
            code: 2,
            msg: msg,
            roomId: type === 1 ? id : -1
        };
        if (type === 2) sendData.userId = id;
        let res = await post(dir + url.send, sendData);
        return JSON.parse(res);
    },
    creatRoom: async (name) => {
        let sendData = {
            code: 5,
            name: name
        };
        let res = await post(dir + url.creatRoom, sendData);
        return JSON.parse(res);
    }
}

const MsgHandle = {
    chatMsg: (data) => {
        console.log("收到聊天消息, 类型[" + (data.msgInfo.tpye === 1 ? "群聊" : "私聊") + "], 消息对象[" + data.msgInfo.sender + "], 消息内容[" + data.msg + "]");
    },
    memberJoin: (data) => {
        console.log("新人入群, 用户名[" + data.name + "], 用户ID[" + data.userId + "]")
    },
    systemMsg: (data) => {
        console.log("系统消息, 类型[" + data.type + "], 内容[" + data.msg + "]");
    },
    wsInitOk: (data) => {
        console.log("绑定ws连接成功");
    }
}

const MsgRoute = {
    7: MsgHandle.chatMsg,
    8: MsgHandle.memberJoin,
    9: MsgHandle.systemMsg,
    16: MsgHandle.wsInitOk
}

function urlEncode(data) {
    let ret = "";
    for (let key in data)
        ret += "&" + key + "=" + encodeURIComponent(data[key])
    return ret;
}

window.onload = () => {
    //msgViewBox.scrolllIntView();
    let ws = null;

    ws = new WebSocket(url.ws);

    ws.onopen = () => {
        console.log("建立websocket连接...");
        let sendData = {};
        sendData = {};
        sendData.code = 1;
        sendData.token = document.cookie;
        ws.send(JSON.stringify(sendData));
    };
    ws.onmessage = event => {
        let data = JSON.parse(event.data);
        MsgRoute[data.code](data);
        console.log(event);
    };

    ws.onclose = () => {
        console.log("websocket连接已关闭");
    }

    document.getElementById("btn-sendMsg").addEventListener('click', async ()=> {
        //console.log(this)
        let msg = document.getElementById("msgBox").value;
        let res = await client.sender(1, 1, msg);
        console.log({sendOk: hex_md5(encodeURIComponent(msg)) === res.msgTag, res: res})
    }, false)
}